package api

import (
	"certificate-manager/pkg/app"
	"certificate-manager/pkg/e"
	"certificate-manager/pkg/log"
	"certificate-manager/pkg/utils"
	"certificate-manager/thirdparty/acmee"
	"certificate-manager/thirdparty/redisc"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

// TriggerTask 手动触发定时任务
func TriggerTask(c *gin.Context) {
	appG := app.Gin{C: c}

	redisClient, err := redisc.GetRedisClientInstance()
	if err != nil {
		log.Logger.Error("【TriggerTask】failed create new redis client.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.RedisError, nil)
		return
	}

	acmeClient, err := acmee.GetAcmeClientInstance()
	if err != nil {
		log.Logger.Error("【TriggerTask】failed create new acme client.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.GetAcmeClientError, nil)
		return
	}

	acmeAccount, err := acmee.GetAcmeAccountInstance(redisClient)
	if err != nil {
		log.Logger.Error("【TriggerTask】failed create new acme account.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.GetAcmeAccountError, nil)
		return
	}

	err = acmee.IssueJob(redisClient, acmeClient, acmeAccount)
	if err != nil {
		log.Logger.Error("【TriggerTask】failed issue job.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.IssueJobError, nil)
		return
	}

	log.Logger.Info("【TriggerTask】issue job success.")
	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
		"msg": "执行成功",
	})
}
